<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Websocket 测试</title>
</head>
<body>

<input type="button" value="打开链接" onclick="openClick();" />
<input type="text" id="txt1" />
<input type="button" value="发送" id="sendBtn" onclick="sendClick();" />
<input type="button" value="关闭" id="closeBtn" onclick="closeClick();" />
<script>
    var url = 'ws://localhost:8888/ws';
    var ws = null;
    //打开链接
    function openClick() {
        ws = new WebSocket(url);
        ws.onopen = function (e) {
            console.log('链接打开');
            ws.send('hello ws');
        }
        ws.onmessage = function (e) {
            console.info('接受到数据：' + e.data);
        }
        ws.onclose = function (e) {
            //e  CloseEvent对象
            //e.code 关闭代码编号标识
            //e.reason 关闭原因
            console.info(e);
            console.log('链接已经关闭');
        }
        ws.onerror = function (e) {
            console.info(e);
            console.log('发生异常:'+e.message);
        }
    }
    //发送
    function sendClick() {
        var content = document.getElementById('txt1').value;
        //如果发送缓冲区没有数据才继续发送
        if (ws.bufferedAmount <= 0) {
            ws.send(content);
        }
    }
    //关闭
    /*
    * 关闭链接说明，在IE浏览器下还会触发 onerror事件
    *  WebSocket Error: Network Error 12030, 与服务器的连接意外终止
    */
    function closeClick() {
        //默认关闭代码 1006
        ws.close();
        ws = null;
        //Uncaught InvalidAccessError: Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999. 1006 is neither.
        //ws.close(3000,'客户端主动关闭');
    }

</script>
</body>
</html>